using System.Collections.Generic;
using System.Linq;
using FluentValidation;
using FubuCore;
using FubuLocalization;
using FubuValidation;

namespace complex.Services
{
    public class FluentValidatorForFubuAdaptor
        : FubuValidation.IValidator
    {
        private readonly ITypeResolver resolver;
        private readonly IValidatorFactory factory;

        public FluentValidatorForFubuAdaptor(ITypeResolver resolver, IValidatorFactory factory)
        {
            this.resolver = resolver;
            this.factory = factory;
        }

        public Notification Validate(object target)
        {
            var type = resolver.ResolveType(target);
            var notification = new Notification(type);
            Validate(target, notification);

            return notification;
        }

        public void Validate(object target, Notification notification)
        {
            factory
                .GetValidator(notification.TargetType)
                .Validate(target)
                .Errors
                .Select(result => result.ErrorMessage)
                .Select(message => StringToken.FromKeyString("", message))
                .Each(token => notification.RegisterMessage(token));
        }
    }
}